import 'package:fig/models/media.dart';
import 'package:fig/views/video/video_control_cover.dart';
import 'package:fig/views/video/video_progress.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

// 播放界面
class VideoPlayerWidget extends StatefulWidget {
  final Media media;

  const VideoPlayerWidget({Key key, @required this.media}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _VideoPlayerWidget();
}

class _VideoPlayerWidget extends State<VideoPlayerWidget> {
  int _selectIndex = 1; // 默认播放第几集
  VideoPlayerController _controller; //先定义一个VideoPlayer的控制器变量
  bool controlCoverHidden = true; // 是否隐藏视频上方的控制遮罩层

  @override
  void initState() {
    super.initState();

    // SystemChrome.setEnabledSystemUIOverlays([]); // 隐藏顶部状态栏
    initPlayer(widget.media.defaultPlayUrl(selectedIndex: _selectIndex));
  }

  @override
  void setState(fn) {
    super.setState(fn);

    final readyPlayUrl = widget.media.defaultPlayUrl(selectedIndex: _selectIndex);

    if (_controller.dataSource != readyPlayUrl) {
      initPlayer(readyPlayUrl);
    }
  }

  @override
  void deactivate() {
    // SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values); // 显示顶部状态栏
    super.deactivate();
  }

  void initPlayer(String playUrl) async {
    _controller?.pause();
    // await _controller?.dispose();

    // 'http://vfx.mtime.cn/Video/2019/03/21/mp4/190321153853126488.mp4',
    // 'http://vfx.mtime.cn/Video/2019/03/19/mp4/190319222227698228.mp4',
    _controller = VideoPlayerController.network(playUrl, videoPlayerOptions: VideoPlayerOptions(mixWithOthers: true));

    _controller.initialize().then((a) {
      print('初始化完成，准备自动播放:${_controller.dataSource}');
      _controller.play();
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    Size screenSize = MediaQuery.of(context).size;
    print('screen width:${screenSize.width} height:${screenSize.height}');

    return WillPopScope(
      child: Scaffold(
        body: Flex(direction: Axis.vertical, children: [
          SizedBox(
            // 最外层嵌套sizedBox是为了控制播放器大小
            width: screenSize.width,
            height: screenSize.width / 16 * 9,
            child: Stack(children: <Widget>[
              Container(color: Colors.black),
              // 播放前的遮罩。如果不设置bottom，会漏出来
              Center(child: Text('          视频加载中，请稍等\n若长时间无法播放，请返回重试', style: TextStyle(color: Colors.red))), // 下面就需有会覆盖当前的
              // 播放器
              Center(child: AspectRatio(aspectRatio: _controller.value.aspectRatio, child: VideoPlayer(_controller))),
              // 挂载字幕？
              ClosedCaption(text: _controller.value.caption.text),
              // 手势识别层
              GestureDetector(
                onTap: () {
                  setState(() {
                    controlCoverHidden = false;
                  });
                },
                child: Container(margin: EdgeInsets.only(bottom: 36), color: Colors.transparent), // 不覆盖下方的进度条（控制条）
              ),
              // 上层暂停遮罩
              Offstage(
                  offstage: controlCoverHidden,
                  child: VideoControlCover(
                    _controller,
                    replayTapCallback: () {
                      Duration duration = _controller.value.position - Duration(seconds: 10);
                      if (duration.inSeconds < 0) {
                        duration = Duration.zero;
                      }
                      _controller.seekTo(duration);
                      _controller.play();
                      setState(() {});
                    },
                    playTapCallback: () {
                      _controller.value.isPlaying ? _controller.pause() : _controller.play();
                      setState(() {});
                    },
                    forwardTapCallback: () {
                      bool ending = false;
                      Duration duration = _controller.value.position + Duration(seconds: 10);
                      if (duration.inSeconds > _controller.value.duration.inSeconds) {
                        ending = true;
                      }

                      _controller.seekTo(duration);
                      ending ? _controller.pause() : _controller.play();
                      setState(() {});
                    },
                    onHidden: () {
                      setState(() {
                        controlCoverHidden = true;
                      });
                    },
                  )),
              // 播放进度
              VideoProgress(_controller), // 进度条
            ]),
          ),
          // 下面是剧集和介绍等内容，放在局部滚动里面
          Flexible(
            child: SingleChildScrollView(
              padding: EdgeInsets.only(left: 8, right: 8, top: 10, bottom: 10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('剧情梗概：', style: TextStyle(fontWeight: FontWeight.bold)),
                  Text(widget.media.description),
                  Center(
                    // 让剧集列表整体居中
                    child: Wrap(
                      spacing: 18.0, // 主轴(水平)方向间距
                      runSpacing: 4.0, // 纵轴（垂直）方向间距
                      alignment: WrapAlignment.start, //剧集标签左对齐
                      children: [
                        for (final anthology in widget.media.anthologyList)
                          ChoiceChip(
                            label: Text(anthology.title, style: TextStyle(fontSize: 12)),
                            selected: anthology.index == _selectIndex ? true : false,
                            onSelected: (selected) {
                              setState(() {
                                _selectIndex = anthology.index;
                              });
                            },
                          )
                      ],
                    ),
                  ),
                  // Center(
                  //   child: Wrap(
                  //     spacing: 10.0, // 主轴(水平)方向间距
                  //     runSpacing: 4.0, // 纵轴（垂直）方向间距
                  //     alignment: WrapAlignment.start, //沿主轴方向居中
                  //     children: [
                  //       for (final anthology in widget.media.anthologyList)
                  //         OutlineButton(
                  //           onPressed: () => print(anthology.playUrl),
                  //           child: Text(anthology.title),
                  //         )
                  //     ],
                  //   ),
                  // ),
                ],
              ),
            ),
          ),
        ]),
      ),
      onWillPop: () async {
        _controller.pause();
        return true;
      },
    );
  }
}
